<template>
  <div>
    <base-table ref="table" :search-params="searchParams" :columns="columnsAction" :async-fc="page" :tree="true">
      <template #tableHeader>
        <t-button @click="insert">{{ t('components.commonTable.insert') }}</t-button>
      </template>
    </base-table>
    <t-dialog v-model:visible="modalOpen" width="45%" @confirm="onModalSubmit">
      <t-form ref="submitFormRef" :rules="rules" :data="submitForm" label-align="top">
        <t-row style="width: 100%" :gutter="[16, 16]">
          <t-col :span="6">
            <t-form-item :label="t('pages.userPermission.type')" name="type">
              <t-select
                v-model="submitForm.type"
                :options="typeOptions"
                :placeholder="t('pages.userPermission.typePlaceholder')"
                @change="chooseType"
              >
              </t-select>
            </t-form-item>
          </t-col>
          <t-col v-if="submitForm.type === 1 || submitForm.type === 2" :span="6">
            <t-form-item :label="t('pages.userPermission.parentId')" name="parentId">
              <t-select
                v-model="submitForm.parentId"
                :options="parentOptions"
                :placeholder="t('pages.userPermission.parentIdPlaceholder')"
              />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userPermission.name')" name="name">
              <t-input v-model="submitForm.name" :placeholder="t('pages.userPermission.namePlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col v-if="submitForm.type !== 2" :span="6">
            <t-form-item :label="t('pages.userPermission.path')" name="path">
              <t-input v-model="submitForm.path" :placeholder="t('pages.userPermission.pathPlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userPermission.nameEn')" name="nameEn">
              <t-input v-model="submitForm.nameEn" :placeholder="t('pages.userPermission.nameEnPlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userPermission.code')" name="code">
              <t-input v-model="submitForm.code" :placeholder="t('pages.userPermission.codePlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col v-if="submitForm.type == 1" :span="6">
            <t-form-item :label="t('pages.userPermission.components')" name="code">
              <t-input v-model="submitForm.components" :placeholder="t('pages.userPermission.componentsPlaceholder')" />
            </t-form-item>
          </t-col>
          <t-col v-if="submitForm.type !== 2" :span="6">
            <t-form-item :label="t('pages.userPermission.outerChain')" name="outerChain">
              <t-radio-group
                v-model="submitForm.outerChain"
                :options="radioOptions"
                :placeholder="t('pages.userPermission.outerChainPlaceholder')"
              />
            </t-form-item>
          </t-col>
          <t-col v-if="submitForm.type !== 2" :span="6">
            <t-form-item :label="t('pages.userPermission.icon')" name="icon">
              <t-select
                v-model="submitForm.icon"
                :placeholder="t('pages.userPermission.iconPlaceholder')"
                :style="{ width: '400px' }"
                :popup-props="{ overlayInnerStyle: { width: '400px' } }"
              >
                <t-option
                  v-for="item in iconOptions"
                  :key="item.stem"
                  :value="item.stem"
                  style="display: inline-block; font-size: 20px"
                >
                  <t-icon :name="item.stem" />
                </t-option>
                <template #valueDisplay
                  ><t-icon :name="submitForm.icon" :style="{ marginRight: '8px' }" />{{ submitForm.icon }}</template
                >
              </t-select>
            </t-form-item>
          </t-col>
          <t-col :span="6">
            <t-form-item :label="t('pages.userPermission.sort')" name="sort">
              <t-input-number
                v-model="submitForm.sort"
                style="width: 100%"
                theme="column"
                :placeholder="t('pages.userPermission.sortPlaceholder')"
              />
            </t-form-item>
          </t-col>
          <t-col :span="12">
            <t-form-item :label="t('pages.userPermission.remark')" name="remark">
              <t-textarea v-model="submitForm.remark" :placeholder="t('pages.userPermission.remarkPlaceholder')" />
            </t-form-item>
          </t-col>
        </t-row>
      </t-form>
    </t-dialog>
  </div>
</template>
<script setup lang="ts">
import { manifest } from 'tdesign-icons-vue-next';
import { DialogPlugin, FormInstanceFunctions, Link, MessagePlugin, Space } from 'tdesign-vue-next';
import { computed, ref } from 'vue';

import { deleteById, insertApi, page, updateApi } from '@/api/sys_permission';
import baseTable from '@/components/base-table/index.vue';
import { t } from '@/locales';

import { getColumns, getRadioOptions, getRules, getSearchParams, getTypeOptions } from './constants';

const parentOptions = ref([]);
const iconOptions = ref(manifest);
const submitForm = ref<_FormData>({});
const modalOpen = ref(false);
const submitFormRef = ref<FormInstanceFunctions>(null);
const table = ref<_TableInstanceFunctions>(null);
const searchParams = computed(() => getSearchParams());
const rules = computed(() => getRules());
const columns = computed(() => getColumns());
const radioOptions = computed(() => getRadioOptions());
const typeOptions = computed(() => getTypeOptions());
const columnsAction = computed(() =>
  columns.value.concat([
    {
      align: 'left',
      fixed: 'right',
      width: 160,
      colKey: 'op',
      title: t('components.commonTable.operation'),
      cell: (h, { row }) =>
        h(
          Space,
          {
            split: 'line',
          },
          () => [
            h(
              Link,
              {
                theme: 'primary',
                underline: false,
                onClick: () => {
                  submitForm.value = row;
                  modalOpen.value = true;
                },
              },
              () => t('components.commonTable.edit'),
            ),
            h(
              Link,
              {
                theme: 'danger',
                underline: false,
                onClick: () => {
                  const confirmDialog = DialogPlugin.confirm({
                    header: t('components.commonTable.tips'),
                    body: t('components.commonTable.deleteConfirm'),
                    confirmBtn: {
                      content: t('components.commonTable.submit'),
                      theme: 'primary',
                      loading: false,
                    },
                    cancelBtn: {
                      content: t('components.commonTable.cancel'),
                      theme: 'default',
                      loading: false,
                    },
                    theme: 'warning',
                    onConfirm: async () => {
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submitting'), loading: true },
                      });
                      await deleteById(row.id);
                      MessagePlugin.success(t('components.commonTable.deleteSuccess'));
                      table.value.onSearch();
                      confirmDialog.update({
                        confirmBtn: { content: t('components.commonTable.submit'), loading: false },
                      });
                      confirmDialog.hide();
                    },
                  });
                },
              },
              () => t('components.commonTable.delete'),
            ),
          ],
        ),
    },
  ]),
);
const insert = () => {
  modalOpen.value = true;
  submitForm.value = {
    outerChain: 0,
  };
};

/**
 * 提交表单
 */
const onModalSubmit = async () => {
  const valid = await submitFormRef.value.validate();
  if (valid && typeof valid !== 'boolean') {
    MessagePlugin.warning(Object.values(valid)[0][0].message);
    return;
  }
  if (submitForm.value.id) {
    await updateApi(submitForm.value);
  } else {
    await insertApi(submitForm.value);
  }
  MessagePlugin.success('操作成功！');
  modalOpen.value = false;
  table.value.onSearch();
};

const chooseType = async (value: any) => {
  if (value === 1) {
    const { records } = await page({
      pageNo: 1,
      pageSize: 99,
      params: {
        type: 0,
      },
    });
    parentOptions.value = records.map((item: any) => ({
      label: item.name,
      value: item.id,
    }));
  } else if (value === 2) {
    const { records } = await page({
      pageNo: 1,
      pageSize: 99,
      params: {
        type: 1,
      },
    });
    parentOptions.value = records.map((item: any) => ({
      label: item.name,
      value: item.id,
    }));
  }
};
</script>
